package org.becomingMd;

import java.io.IOException;
import java.net.*;
import java.util.Enumeration;

public class Send_Local_IP_Address extends Thread {
    private static final int PORT = 12745; // 服务端监听端口
    private static final int RETRY_INTERVAL = 200; // 重试间隔（毫秒）

    @Override
    public void run() {
        // 获取设备的局域网 IP 地址
        String localIpAddress = getLocalIpAddress();
        // 构造广播地址
        String broadcastAddress = getBroadcastAddress(localIpAddress);

        while (true) {
            //System.out.println("发送广播");
            try (DatagramSocket clientSocket = new DatagramSocket()) {
                clientSocket.setBroadcast(true); // 启用广播
                // 发送广播请求
                DatagramPacket packet = new DatagramPacket(localIpAddress.getBytes(), localIpAddress.length(),
                        InetAddress.getByName(broadcastAddress), PORT);
                clientSocket.send(packet);

                // 等待服务端回复
                byte[] buffer = new byte[1024];
                DatagramPacket responsePacket = new DatagramPacket(buffer, buffer.length);
                clientSocket.setSoTimeout(RETRY_INTERVAL); // 设置超时时间
                clientSocket.receive(responsePacket);

                // 获取客户端的IP地址和端口号
                InetAddress clientAddress = responsePacket.getAddress();
                int clientPort = responsePacket.getPort();

                // 解析客户端消息
                String clientMessage = new String(responsePacket.getData(), 0, responsePacket.getLength()).trim();

                // 打印客户端的IP地址、端口号和消息
                System.out.println("收到客户端回复,连接成功: " + clientMessage +
                        ", 客户端IP地址: " + clientAddress.getHostAddress() +
                        ", 客户端端口号: " + clientPort);




            } catch (IOException e) {
              //  System.out.println("广播/监听失败: " + e.getMessage());
            }
            try {
                Thread.sleep(2000); // 休眠两秒
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
    private static String getLocalIpAddress() {
        try {
            Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
            while (en.hasMoreElements()) {
                NetworkInterface intf = en.nextElement();
                // 检查网络接口名称，确保是无线局域网适配器
                if (intf.getName().toLowerCase().contains("wlan") || intf.getName().toLowerCase().contains("wifi")) {
                    Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();
                    while (enumIpAddr.hasMoreElements()) {
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        if (!inetAddress.isLoopbackAddress() && inetAddress instanceof java.net.Inet4Address) {
                            return inetAddress.getHostAddress();
                        }
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return "127.0.0.1";
    }
    private static String getBroadcastAddress(String localIpAddress) {
        try {
            // 将 IP 地址分成字节数组
            String[] ipParts = localIpAddress.split("\\.");
            if (ipParts.length != 4) {
                return null;
            }

            // 构造广播地址（将最后一部分设置为255）
            return ipParts[0] + "." + ipParts[1] + "." + ipParts[2] + ".255";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
